﻿using System.Collections;
using FlowCanvas.Nodes;
using ParadoxNotion.Design;
using UnityEngine;

namespace Snake.Gameplay.GameplayFlowExtension
{
    [Category("Animation")]
    [Description("Wait for a state finish")]
    public class AnimatorPlayState : LatentActionNode<Animator, string>
    {
        public float TimeLeft { get; private set; }
        public float Normalized { get; private set; }

        private Animator Animator { get; set; }

        private const string DefaultState = "Empty";

        public override IEnumerator Invoke(Animator animator, string state)
        {
            Animator = animator;
            Animator.Play(state);
            Animator.Update(0f);
            var time = Animator.GetCurrentAnimatorStateInfo(0).length;
            TimeLeft = time;
            while (TimeLeft > 0f)
            {
                TimeLeft = time - parentNode.elapsedTime;
                TimeLeft = Mathf.Max(TimeLeft, 0f);
                Normalized = 1f - TimeLeft / time;
                yield return null;
            }

            ResetState();
        }

        private void ResetState()
        {
            Animator.Play(DefaultState);
            Animator.Update(0f);
        }

        public override void OnBreak()
        {
            ResetState();
        }
    }
}